package com.example.androidproject.app.deprecated;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.example.androidproject.myview.MyGridView;
import com.example.androidproject.myview.MyListView;
import com.example.androidproject.myview.MyScrollView;
import com.example.androidproject.R;
import com.example.androidproject.app.deprecated.temporarily_deprecated_adapter.ClassifyContentAdapter;
import com.example.androidproject.app.adapter.ClassifyOptionsAdapter;
import com.example.androidproject.app.classifybean.ClassifyBean;
import com.example.androidproject.movie.bean.ResultBeanData;
import com.example.androidproject.novel.bean.NovelBean;
import com.example.androidproject.utils.RequestConstant;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.CountDownLatch;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 弃用
 */

public class ClassifyActivity extends Activity {
    private OkHttpClient okHttpClient;
    private MyGridView gv_classify_nav;
    private MyListView list_classify_content;
    private TextView tv_classify_options_all;
    //    private NestedScrollView sv_classify;
    private MyScrollView sv_classify;
    private int classifyFlag;
    private String TAG = "GGSTUDY";
    //    ArrayList<ResultBeanData.DataBean> dataList = new ArrayList<>();
    ArrayList<ResultBeanData.DataBean> dataListMovie = new ArrayList<>();
    ArrayList<NovelBean.DataBean> dataListNovel = new ArrayList<>();
    private int limit = 15;
    private int page = 1;
    private int total;
    private boolean isLoading = false;
    private LinearLayout ll_contentLoding;
    private TextView btn_classify_options_all1;

    CountDownLatch latch = new CountDownLatch(2);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_classity);
        okHttpClient = new OkHttpClient();

        Intent intent = getIntent();
        classifyFlag = intent.getIntExtra("flag", 0);

        getOptions();
        getContent("全部");
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        initView();
        initPage();

    }

    private void initView() {
        gv_classify_nav = findViewById(R.id.gv_classify_nav);
        tv_classify_options_all = findViewById(R.id.tv_classify_options_all);
        list_classify_content = findViewById(R.id.list_classify_content);
        sv_classify = findViewById(R.id.sv_classify);
        ll_contentLoding = findViewById(R.id.ll_contentLoding);
        btn_classify_options_all1 = findViewById(R.id.btn_classify_options_all1);
    }

    private void initPage() {
        initListener();
    }

    @SuppressLint("ClickableViewAccessibility")
    private void initListener() {
        tv_classify_options_all.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(ClassifyActivity.this, "全部", Toast.LENGTH_SHORT).show();
            }
        });
        ll_contentLoding.setVisibility(View.VISIBLE);
        sv_classify.onScrollViewScrollToBottom(new MyScrollView.OnScrollBottomListener() {
            @Override
            public void scrollToBottom() {
                // 这里做加载动作
                if (limit * page >= total) {
                    Toast.makeText(ClassifyActivity.this, "数据已经加载完了", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (isLoading) {
                    ll_contentLoding.setVisibility(View.VISIBLE);
                    return;
                } else {
                    ll_contentLoding.setVisibility(View.GONE);
                }
                page += 1;
                getContent("全部");
            }
        });
    }

    private void getOptions() {
        String classify = "电影";
        if (classifyFlag == 1) {
            classify = "电影";
        }
        if (classifyFlag == 2) {
            classify = "小说";
        }
        String url = RequestConstant.CLASSIFY_URL + "?" + "classify=" + classify;
//        Log.d(TAG, "getOptions: " + url);
        Request request = new Request.Builder().url(url).build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.d(TAG, "onFailure: " + e);
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (response.isSuccessful()) {
                    copeData(response.body().string(), 1);
                    latch.countDown();
                }
            }
        });
    }

    private void getContent(String classify) {
//        String classify = "全部";
//        limit = 10;
//        page = 1;
        isLoading = true;
        String url = "";
//        ll_contentLoding.setVisibility(View.VISIBLE);
        if (classifyFlag == 1) {
            url = RequestConstant.MOVIE_IMG_URL + "?" + "classify=" + classify + "&" + "limit=" + limit + "&" + "page=" + page;
        }
        if (classifyFlag == 2) {
            url = RequestConstant.NOVEL_URL + "?" + "classify=" + classify + "&" + "limit=" + limit + "&" + "page=" + page;
        }
        Request request = new Request.Builder().url(url).build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.d(TAG, "onFailure: " + e);
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String result = response.body().string();
                copeData(result, 2);
                latch.countDown();
            }
        });
    }

    private void copeData(String json, int getflag) {
        Gson gson = new Gson();
        ClassifyBean classifyBean = gson.fromJson(json, ClassifyBean.class);
        ArrayList<ClassifyBean.DataBean> data = (ArrayList<ClassifyBean.DataBean>) classifyBean.getData();
        /**
         *  bean怎么能公用呢 数据都不一样 所以这里得通过flag判断然后再进行不同bean类选择
         */
        ResultBeanData resultBeanData = null;
        NovelBean novelBean = null;
        ArrayList<ResultBeanData.DataBean> contentMovie = null;
        ArrayList<NovelBean.DataBean> contentNovel = null;
        if (classifyBean.getStatus() == 0) {
            if (data != null) {
                Message message = new Message();
                Bundle bundle = new Bundle();
                bundle.putParcelableArrayList("data", data);
                //
                if (classifyFlag == 1) {
                    resultBeanData = gson.fromJson(json, ResultBeanData.class);
                    contentMovie = (ArrayList<ResultBeanData.DataBean>) resultBeanData.getData();
                    bundle.putParcelableArrayList("contentMovie", contentMovie);
                    total = resultBeanData.getTotal();
                }
                if (classifyFlag == 2) {
                    novelBean = gson.fromJson(json, NovelBean.class);
                    contentNovel = (ArrayList<NovelBean.DataBean>) novelBean.getData();
                    bundle.putParcelableArrayList("contentNovel", contentNovel);
                    total = novelBean.getTotal();
                }
                message.setData(bundle);
                if (getflag == 1) {
                    // 获取分类导航栏
                    classifyHandler.sendMessage(message);
                }
                if (getflag == 2) {
                    // 获取内容
                    contentHandler.sendMessage(message);
                }
            } else {
                Toast.makeText(this, "数据为空", Toast.LENGTH_SHORT).show();
            }
        } else {
            Log.d(TAG, "请求失败");
        }
    }

    @SuppressLint("HandlerLeak")
    public Handler classifyHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            ArrayList<ClassifyBean.DataBean> data = msg.getData().getParcelableArrayList("data");
            ClassifyOptionsAdapter classifyOptionsAdapter = new ClassifyOptionsAdapter(ClassifyActivity.this, data, classifyFlag, btn_classify_options_all1);
            gv_classify_nav.setAdapter(classifyOptionsAdapter);
            gv_classify_nav.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Toast.makeText(ClassifyActivity.this, "" + position, Toast.LENGTH_SHORT).show();
                }
            });
        }
    };

    private ClassifyContentAdapter classifyContentAdapter;
    @SuppressLint("HandlerLeak")
    public Handler contentHandler = new Handler() {
        @SuppressLint("ClickableViewAccessibility")
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            // 这里也需要 flag 判断时电影还是小说还是壁纸
            ArrayList<ResultBeanData.DataBean> dataMovie = null;
            ArrayList<NovelBean.DataBean> dataNovel = null;
            isLoading = false;
            if (classifyFlag == 1) {
                dataMovie = msg.getData().getParcelableArrayList("contentMovie");
                dataListMovie.addAll(dataMovie);
            }
            if (classifyFlag == 2) {
                dataNovel = msg.getData().getParcelableArrayList("contentNovel");
                dataListNovel.addAll(dataNovel);
            }
            if (classifyContentAdapter == null) {
                if (classifyFlag == 1) {
                    classifyContentAdapter = new ClassifyContentAdapter(ClassifyActivity.this, dataListMovie, classifyFlag);
                }
                if (classifyFlag == 2) {
//                    classifyContentAdapter = new ClassifyContentAdapter(ClassifyActivity.this, dataListNovel, classifyFlag);
                }
                list_classify_content.setAdapter(classifyContentAdapter);
            } else {
                classifyContentAdapter.notifyDataSetChanged();
            }
            classifyContentAdapter.setNumColumns(3);
            ll_contentLoding.setVisibility(View.GONE);
//            跳转到详情页的 需要一个flag 来判定 执行电影小说还是壁纸
        }
    };
}
